package com.animallife.android.ui;

import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.animallife.android.R;
import com.animallife.android.db.AnimalColumns;
import com.animallife.android.db.AnimalQuery;
import com.animallife.android.imLoader.ImageLoaderNew;
import com.animallife.android.model.Animals;
import com.animallife.android.music.AndroidAudio;
import com.animallife.android.music.Music;
import com.animallife.android.service.UpdateService;
import com.animallife.android.util.Config;
import com.animallife.android.util.DetachableResultReceiver;
import com.animallife.android.util.DetachableResultReceiver.Receiver;
import com.animallife.android.util.NotifyingAsyncQueryHandler;
import com.animallife.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.flurry.android.FlurryAgent;

public class DetailActivity extends Activity implements AsyncQueryListener, Receiver, TextToSpeech.OnInitListener {

	private NotifyingAsyncQueryHandler asyncHandler;
	private TextView animalName;
	private TextView txtFamily;
	private TextView txtClass;
	private TextView txtColor;
	private TextView txtHabitat;
	private TextView txtLifeTime;
	private TextView txtLocation;
	private TextView txtFood;
	private TextView txtSize;
	private TextView txtWeight;
	private TextView txtSkin;
	private TextView txtSpeed;
	private Gallery gallery;
	private TextToSpeech mTts;
	private ImageButton sayButton;
	private ImageButton btnLeft;
	private ImageButton btnRight;
	private Cursor mCursor;
	private String sound = null;
	private Music music;
	private AndroidAudio androidAudio;
	private ImageButton buttonSound;

	private ImageLoaderNew imLoader;
	private final int DIALOG_NO_TTS_ID = 1;

	private DetachableResultReceiver receiver;
	private String[] ImgURL = new String[4];
	private long id;
	private int position = 0;
	private String name;

	public void onStart() {
		super.onStart();
		FlurryAgent.onStartSession(this, "CJVA21QV9JQKNUQS93F9");
	}

	public void onStop() {
		super.onStop();
		FlurryAgent.onEndSession(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details_layout);
		animalName = (TextView) findViewById(R.id.animalName);
		txtFamily = (TextView) findViewById(R.id.txtFamily);
		txtClass = (TextView) findViewById(R.id.txtClass);
		txtColor = (TextView) findViewById(R.id.txtColor);
		txtHabitat = (TextView) findViewById(R.id.txtHabitat);
		txtLifeTime = (TextView) findViewById(R.id.txtLifeTime);
		txtLocation = (TextView) findViewById(R.id.txtLocation);
		txtFood = (TextView) findViewById(R.id.txtFood);
		txtSize = (TextView) findViewById(R.id.txtSize);
		txtWeight = (TextView) findViewById(R.id.txtWeight);
		txtSkin = (TextView) findViewById(R.id.txtSkin);
		txtSpeed = (TextView) findViewById(R.id.txtSpeed);
		btnLeft = (ImageButton) findViewById(R.id.btnLeft);
		btnRight = (ImageButton) findViewById(R.id.btnRight);
		imLoader = new ImageLoaderNew(DetailActivity.this);
		buttonSound = (ImageButton) findViewById(R.id.buttonSound);

		androidAudio = new AndroidAudio(DetailActivity.this);

		id = getIntent().getLongExtra(Config._ID, 0L);
		String selectionArgs = getIntent().getStringExtra(Config.ANIMAL_TYPE);

		sayButton = (ImageButton) findViewById(R.id.btnSpeak);

		sayButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mTts == null) {
					mTts = new TextToSpeech(DetailActivity.this, DetailActivity.this);
				} else {
					sayAnimalName();
				}
			}
		});
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		asyncHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		asyncHandler.startQuery(AnimalQuery._TOKEN, Animals.CONTENT_URI, AnimalQuery.PROJECTION, AnimalColumns.ISENABLE
				+ "  = 1 AND " + AnimalColumns.ANIMAL_CLASS + " = '" + selectionArgs + "'", null, Animals.NAME_SORT);

	}

	private void fetchImages(String animalName) {
		Intent testIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateService.class);
		testIntent.putExtra(UpdateService.EXTRA_STATUS_RECEIVER, receiver);
		testIntent.putExtra(UpdateService.EXTRA_REQUEST_CODE, Config.IMAGE_FETCH);
		testIntent.putExtra(Config.ANIMAL_NAME, animalName);
		startService(testIntent);
	}

	@Override
	public void onDestroy() {
		if (mTts != null) {
			mTts.stop();
			mTts.shutdown();
		}
		
		if (null != mCursor)
			mCursor.close();

		super.onDestroy();
	}

	public void onInit(int status) {
		Log.e("Text To Speach", "Init");
		if (status == TextToSpeech.SUCCESS) {
			int result = mTts.setLanguage(Locale.ENGLISH);
			if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
				showDialog(DIALOG_NO_TTS_ID);
				Log.e("", "Language is not available.");
			} else {
				sayAnimalName();
			}
		} else {
			Log.e("", "Could not initialize TextToSpeech.");
		}
	}

	private void sayAnimalName() {
		mTts.speak(animalName.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {

		if (null != cursor && cursor.moveToFirst()) {
			do {
				if (id == cursor.getInt(AnimalQuery._ID))
					break;
			} while (cursor.moveToNext());

			position = cursor.getPosition();

			if (cursor.moveToPosition(cursor.getPosition())) {
//				startManagingCursor(cursor);
				mCursor = cursor;
				initView(cursor);

			}
		}
	}

	private void initView(Cursor cursor) {
		name = cursor.getString(AnimalQuery.NAME);
		animalName.setText(name);
		txtFamily.setText(cursor.getString(AnimalQuery.FAMILY));
		txtClass.setText(cursor.getString(AnimalQuery.ANIMAL_CLASS));
		txtColor.setText(cursor.getString(AnimalQuery.COLOUR));
		txtHabitat.setText(cursor.getString(AnimalQuery.HABIAT));
		txtLifeTime.setText(cursor.getString(AnimalQuery.LIFE_SPAN));
		txtLocation.setText(cursor.getString(AnimalQuery.LOCATION));
		txtFood.setText(cursor.getString(AnimalQuery.PREY));
		txtSize.setText(cursor.getString(AnimalQuery.SIZE));
		txtWeight.setText(cursor.getString(AnimalQuery.WEIGHT));
		txtSkin.setText(cursor.getString(AnimalQuery.SKIN_TYPE));
		txtSpeed.setText(cursor.getString(AnimalQuery.TOP_SPEED));
		sound = cursor.getString(AnimalQuery.SOUND);
		if (sound == null)
			buttonSound.setVisibility(View.GONE);
		else
			buttonSound.setVisibility(View.VISIBLE);

		if (position == 0)
			btnLeft.setEnabled(false);
		else if (position == mCursor.getCount() - 1)
			btnRight.setEnabled(false);

		fetchImages(cursor.getString(AnimalQuery.NAME));
	}

	public void forwardWiki(View view) {

		Intent intent = new Intent(DetailActivity.this, WikiActivity.class);
		intent.putExtra(Config.ANIMAL_NAME, name);
		startActivity(intent);
	}

	public void prevAnimal(View view) {
		if (null != mCursor && mCursor.moveToPrevious()) {
			initView(mCursor);
			view.setEnabled(!(mCursor.getPosition() == 0));
			btnRight.setEnabled(true);
		}

	}

	public void nextAnimal(View view) {
		if (null != mCursor && mCursor.moveToNext()) {
			initView(mCursor);
			view.setEnabled(!(mCursor.getPosition() == mCursor.getCount() - 1));
			btnLeft.setEnabled(true);
		}
	}

	public void playSound(View view) {
		// TODO
		music = androidAudio.newMusic("sounds/" + sound);
		music.setLooping(false);
		music.setVolume(1.9f);
		music.play();

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateService.STATUS_RUNNING:
			break;
		case UpdateService.STATUS_ERROR:
			break;
		case UpdateService.STATUS_FINISHED:

			if (resultData.containsKey(Config.URLS_ARRAY)) {
				ImgURL = resultData.getStringArray(Config.URLS_ARRAY);
				gallery = (Gallery) findViewById(R.id.animalGallery);
				gallery.setAdapter(new AddImgAdp(this));

			}

			break;
		}
	}

	public class AddImgAdp extends BaseAdapter {
		int GalItemBg;
		private Context cont;

		public AddImgAdp(Context c) {
			cont = c;
		}

		public int getCount() {
			return ImgURL.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imgView = new ImageView(cont);
			imgView.setLayoutParams(new Gallery.LayoutParams(-1, -1));
			imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			imLoader.displayImage(ImgURL[position], DetailActivity.this, imgView);
			return imgView;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		switch (id) {
		case DIALOG_NO_TTS_ID:
			builder.setMessage(getString(R.string.tts));
			builder.setNeutralButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			});
			builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Intent installIntent = new Intent();
					installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
					startActivity(installIntent);
				}
			});
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}
}
